package com.apex.oauth.security.ice.component;

import com.apex.common.util.DigestUtil;
import com.apex.oauth.security.domian.TBsdtUserRepository;
import com.apex.oauth.security.ice.granted.Openid;
import com.apex.oauth.security.service.impl.UserInformationServiceImpl;
import com.apex.security.api.entity.TBsdtWxUser;
import com.apex.security.api.entity.TUser;
import com.jsoniter.output.JsonStream;
import com.wiscom.is.IdentityFactory;
import com.wiscom.is.IdentityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Create by IntelliJ IDEA
 * 用户：王建
 * 日期：2018-4-3
 */
public class CustomUserAuthenticationManager implements AuthenticationProvider {

    @Value("${sso.ice.file.path}")
    private String iceFilePath;

    @Autowired
    private UserInformationServiceImpl userInformationService;

    @Autowired
    private TBsdtUserRepository repository;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        List<GrantedAuthority> authorities = new ArrayList<>();
        boolean info=false;
        String username=authentication.getName();
        if(StringUtils.isEmpty(username)){
            throw new BadCredentialsException("用户名登录账号不能为空！");
        }
        String password= (String) authentication.getCredentials();
        String openid="";
        List<Openid> list= (List<Openid>) authentication.getAuthorities();
        if (null!=list&&list.size()>0){
            openid=list.get(0).getAuthority();
        }
        if(StringUtils.isEmpty(password)){
            throw new BadCredentialsException("登录密码不能为空！");
        }
        try {
            TUser user=userInformationService.findByLoginId(username);
            if(null!=user){
                IdentityFactory factory=IdentityFactory.createFactory(iceFilePath);
                IdentityManager manager=factory.getIdentityManager();
                password=DigestUtil.md5(password);
                info=manager.checkPassword(user.getUserid(),password);
            }
            if(!StringUtils.isEmpty(username)&&!StringUtils.isEmpty(openid)){
                TBsdtWxUser wxUser=new TBsdtWxUser();
                wxUser.setOpenid(openid);
                wxUser.setUserid(username);
                wxUser.setPwd(password);
                wxUser.setCookie(DigestUtil.md5(openid+password));
                Map<String,Object> map=new HashMap<>();
                map.put("data",wxUser);
                repository.save(JsonStream.serialize(map));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));//默认全部为admin权限
        authorities.add(new Openid(openid));
        if(info){
            return new UsernamePasswordAuthenticationToken(authentication.getName(),password,authorities);
        }
        // 没有通过认证则抛出密码错误异常
        throw new BadCredentialsException("用户名或者密码错误！");
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return UsernamePasswordAuthenticationToken.class.equals(authentication);
    }
}
